//
//  LookingForViewController.m
//  HotWord
//
//  Created by 贺 欢 on 13-3-2.
//
//

#import "LookingForViewController.h"
#import "SchoolRankingViewController.h"

typedef enum
{
    DataPickerTypeTime = 0,
    DataPickerTypeAddress
}DataPickerType;


@interface LookingForViewController ()<UIGestureRecognizerDelegate,UIPickerViewDelegate, UIPickerViewDataSource,SchoolRankingViewControllerDelegate>
{
    User *_user;
    DataPickerType *_dataPickerType;
    Match *_selectedMath;
}
@property (retain, nonatomic) IBOutlet UIView *containerView;
@property (retain, nonatomic) IBOutlet UIButton *dreamSchoolBtn;
@property (retain, nonatomic) IBOutlet UILabel *dreamSchoolLabel;
@property (retain, nonatomic) IBOutlet UIButton *findTeacherBtn;
@property (retain, nonatomic) IBOutlet UIButton *SATBtn;
@property (retain, nonatomic) IBOutlet UIButton *timeBtn;
@property (retain, nonatomic) IBOutlet UIButton *addressBtn;
@property (retain, nonatomic) IBOutlet UIView *pickContainerView;
@property (retain, nonatomic) IBOutlet UIPickerView *dataSelectPicker;
@property (retain, nonatomic) IBOutlet UIView *SATContainerView;

@end

@implementation LookingForViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithUser:(User *)user
{
    self = [super init];
    if (self)
    {
        _user = [user retain];
        _selectedMath = [[Match alloc] init];
        _selectedMath.matchType = _user.match.matchType;
        _selectedMath.dreamschool = _user.match.dreamschool;
        _selectedMath.examYear = _user.match.examYear;
        _selectedMath.examMonth = _user.match.examMonth;
        _selectedMath.examAddress = _user.match.examAddress;

    }
    return self;
}

- (void)viewDidUnload
{
    [self setDreamSchoolBtn:nil];
    [self setDreamSchoolLabel:nil];
    [self setFindTeacherBtn:nil];
    [self setSATBtn:nil];
    [self setTimeBtn:nil];
    [self setAddressBtn:nil];
    [self setPickContainerView:nil];
    [self setDataSelectPicker:nil];
    [self setSATContainerView:nil];
    [self setContainerView:nil];
    [super viewDidUnload];
}

- (void)dealloc
{
    [_dreamSchoolBtn release];
    [_dreamSchoolLabel release];
    [_findTeacherBtn release];
    [_SATBtn release];
    [_timeBtn release];
    [_addressBtn release];
    [_pickContainerView release];
    [_dataSelectPicker release];
    [_selectedMath release];
    [_SATContainerView release];
    [_containerView release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _containerView.top = self.view.height;
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hanldTapGesture:)];
    tapGestureRecognizer.delegate = self;
    [self.view addGestureRecognizer:tapGestureRecognizer];
    [tapGestureRecognizer release];
    [self setButtonSelectedStatus];
    [self setMatchInfo];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.view viewWithTag:10].alpha = 0;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [UIView animateWithDuration:0.4
                     animations:^{
                         _containerView.top = 0;
                         [self.view viewWithTag:10].alpha = 1;
                     }];
}


- (void)setMatchInfo
{
//    if (IS_STRING_NOT_EMPTY(_user.match.dreamschool))
//    {
//        _dreamSchoolLabel.text = _user.match.dreamschool;
//    }
    
    if (![@"SAT" isEqualToString:_user.exam])
    {
        _SATContainerView.hidden = YES;
        return;
    }
    
    if (IS_STRING_NOT_EMPTY(_user.match.examYear) && IS_STRING_NOT_EMPTY(_user.match.examMonth) )
    {
        NSString *time = [NSString stringWithFormat:@"%@年%@月",_user.match.examYear,_user.match.examMonth];
        [_timeBtn setTitle:time forState:UIControlStateNormal];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy年M月"];
        NSDate *examTime = [dateFormatter dateFromString:time];
        
        NSDate *currentDate = [NSDate date];
        currentDate = [dateFormatter dateFromString:[dateFormatter stringFromDate:currentDate]];
        [dateFormatter release];
        
        if ([examTime compare:currentDate] == NSOrderedAscending)
        {
            [_timeBtn setTitle:@"时间" forState:UIControlStateNormal];
            _selectedMath.examYear = nil;
            _selectedMath.examMonth = nil;
            _SATBtn.selected = NO;
        }
    }
    
    if (IS_STRING_NOT_EMPTY(_user.match.examAddress))
    {
        [_addressBtn setTitle:_user.match.examAddress forState:UIControlStateNormal];
    }
    
}

- (void)setButtonSelectedStatus
{
    NSInteger type = 0;
    if (_user.match.matchType)
    {
        type = [_user.match.matchType integerValue];
    }
    
    _dreamSchoolBtn.selected = NO;
    _findTeacherBtn.selected = NO;
    _SATBtn.selected = NO;
    
    switch (type)
    {
        case 0:
            break;
        case 1:
            _dreamSchoolBtn.selected = YES;
            break;
        case 2:
            _findTeacherBtn.selected = YES;
            break;
        case 3:
            _SATBtn.selected = YES;
            break;
        default:
            break;
    }
}


#pragma mark - IBAction

- (IBAction)tapOnBackBtn:(id)sender
{
    if (_dreamSchoolBtn.selected)
    {
        _selectedMath.matchType = @"1";
    }
    
    if (_findTeacherBtn.selected)
    {
        _selectedMath.matchType = @"2";
    }
    
    if (_SATBtn.selected)
    {
        _selectedMath.matchType = @"3";

    }
    
    if (!_dreamSchoolBtn.selected && !_findTeacherBtn.selected && !_SATBtn.selected)
    {
        _selectedMath.matchType = @"0";
    }
    
    BOOL haChangeInfo = NO;
    if ([_selectedMath.matchType isEqualToString:_user.match.matchType])
    {
        switch ([_selectedMath.matchType integerValue])
        {
            case 0:
                break;
            case 1:
//                if (![_selectedMath.dreamschool isEqualToString:_user.match.dreamschool])
//                {
//                    haChangeInfo = YES;
//                }
                break;
            case 2:
                break;
            case 3:
                if (![_selectedMath.examYear isEqualToString:_user.match.examYear] || ![_selectedMath.examMonth isEqualToString:_user.match.examMonth] || ![_selectedMath.examAddress isEqualToString:_user.match.examAddress])
                {
                    haChangeInfo = YES;
                }
                break;
            default:
                break;
        }
    }
    else
    {
        haChangeInfo = YES;
    }

    
    if (_delegate && [_delegate respondsToSelector:@selector(lookingForViewController:didSelectMatch:)] && haChangeInfo)
    {
        [_delegate lookingForViewController:self didSelectMatch:_selectedMath];
    }
    
    
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)tapOnDeamSchoolBtn:(id)sender
{
//    _dreamSchoolBtn.highlighted = NO;
//    _dreamSchoolBtn.selected = YES;
//    _findTeacherBtn.selected = NO;
//    _SATBtn.selected = NO;
//    
//    SchoolRankingViewController *schoolRankingViewController = [[SchoolRankingViewController alloc] init];
//    schoolRankingViewController.delegate = self;
//    [self.navigationController pushViewController:schoolRankingViewController animated:YES];
//    [schoolRankingViewController release];
    
    _dreamSchoolBtn.highlighted = NO;
    _dreamSchoolBtn.selected = !_dreamSchoolBtn.selected;
    if (_dreamSchoolBtn.selected)
    {
        _findTeacherBtn.selected = NO;
        _SATBtn.selected = NO;
        
    }
}
- (IBAction)tapOnFindTeacherBtn:(id)sender
{
    _findTeacherBtn.highlighted = NO;
    _findTeacherBtn.selected = !_findTeacherBtn.selected;
    if (_findTeacherBtn.selected)
    {
        _dreamSchoolBtn.selected = NO;
        _SATBtn.selected = NO;
        
    }

}
- (IBAction)tapOnSATBtn:(id)sender
{
    _SATBtn.highlighted = NO;

    if (IS_STRING_NOT_EMPTY(_selectedMath.examYear) && IS_STRING_NOT_EMPTY(_selectedMath.examMonth) && IS_STRING_NOT_EMPTY(_selectedMath.examAddress))
    {
        _SATBtn.selected = !_SATBtn.selected;
        if (_SATBtn.selected)
        {
            _dreamSchoolBtn.selected = NO;
            _findTeacherBtn.selected = NO;
            
        }

    }
    else
    {
        _SATBtn.selected = NO;
        _dreamSchoolBtn.selected = NO;
        _findTeacherBtn.selected = NO;
        [self tapOnTimeBtn:nil];
    }

}
- (IBAction)tapOnTimeBtn:(id)sender
{
    _dataPickerType = DataPickerTypeTime;
    
    [self.dataSelectPicker reloadAllComponents];

    if (IS_STRING_NOT_EMPTY(_selectedMath.examYear) && IS_STRING_NOT_EMPTY(_selectedMath.examMonth))
    {
        [self setDefaultPickerSelectRowWithArray:TEST_YEAR_ARRAY defaultTitle:_selectedMath.examYear];
        [self setDefaultPickerSelectRowWithDefaultTitle:_selectedMath.examMonth];
    }
    
    [self showDataPicker];
    
}
- (IBAction)tapOnAddressBtn:(id)sender
{
    _dataPickerType = DataPickerTypeAddress;
    [self.dataSelectPicker reloadAllComponents];

    if (IS_STRING_NOT_EMPTY(_selectedMath.examAddress))
    {
        [self setDefaultPickerSelectRowWithArray:SAT_TEST_ADDRESS defaultTitle:_selectedMath.examAddress];
    }
    [self showDataPicker];
}

- (void)setDefaultPickerSelectRowWithArray:(NSArray *)array defaultTitle:(NSString *)defaultTitle
{
    for (NSString *title in array)
    {
        if ([defaultTitle isEqualToString:title])
        {
            [self.dataSelectPicker selectRow:[array indexOfObject:title] inComponent:0 animated:NO];
            break;
        }
    }
}

- (void)setDefaultPickerSelectRowWithDefaultTitle:(NSString *)defaultTitle
{
    NSString *selectYear = [TEST_YEAR_ARRAY objectAtIndex:[_dataSelectPicker selectedRowInComponent:0]];
    NSArray *months = [self getMonthForYear:selectYear];
    for (NSString *month in months)
    {
        if ([defaultTitle isEqualToString:month])
        {
            [self.dataSelectPicker selectRow:[months indexOfObject:month] inComponent:1 animated:NO];
            break;
        }
    }
}


- (void)showDataPicker
{
    [self.dataSelectPicker reloadAllComponents];
    [UIView animateWithDuration:0.3
                     animations:^{
                         self.pickContainerView.bottom = self.view.height;
                     }];
    
}

- (IBAction)tapOnCancel:(id)sender
{
    [UIView animateWithDuration:0.3
                     animations:^{
                         _pickContainerView.top = self.view.height;
                     }];

}


- (IBAction)tapOnConfirmBtn:(id)sender
{
    if (_dataPickerType == DataPickerTypeTime)
    {
        NSString *selectYear = [TEST_YEAR_ARRAY objectAtIndex:[_dataSelectPicker selectedRowInComponent:0]];        
        NSArray *months = [self getMonthForYear:selectYear];
        NSString *selectMonth = [months objectAtIndex:[_dataSelectPicker selectedRowInComponent:1]];
        [_timeBtn setTitle:[NSString stringWithFormat:@"%@年%@月",selectYear,selectMonth] forState:UIControlStateNormal];
        _selectedMath.examYear = selectYear;
        _selectedMath.examMonth = selectMonth;
        
    }
    else
    {
        _selectedMath.examAddress = [SAT_TEST_ADDRESS objectAtIndex:[_dataSelectPicker selectedRowInComponent:0]];
        [_addressBtn setTitle:_selectedMath.examAddress forState:UIControlStateNormal];

    }
    
    if (IS_STRING_NOT_EMPTY(_selectedMath.examYear) && IS_STRING_NOT_EMPTY(_selectedMath.examMonth) && IS_STRING_NOT_EMPTY(_selectedMath.examAddress))
    {
        _SATBtn.selected = YES;
        _dreamSchoolBtn.selected = NO;
        _findTeacherBtn.selected = NO;
    }
    else
    {
        _SATBtn.selected = NO;
    }
    
    [self tapOnCancel:nil];
}

#pragma mark - UIGestureRecognizerDelegate

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([touch.view isKindOfClass:[UIButton class]] || [touch.view isDescendantOfView:self.pickContainerView]) {
        return NO;
    }
    return YES;
}

- (void)hanldTapGesture:(UIGestureRecognizer *)recognizer
{
    [self tapOnCancel:nil];
}

#pragma mark - UIPickerViewDataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    if (_dataPickerType == DataPickerTypeTime)
    {
        return 2;
    }
    return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (_dataPickerType == DataPickerTypeTime)
    {
        NSArray *yearsArray = TEST_YEAR_ARRAY;
        if (component == 0)
        {
            return [yearsArray count];
        }
        else
        {
            NSUInteger selectedRow = [pickerView selectedRowInComponent:0];
            NSString *selectYear = [yearsArray objectAtIndex:selectedRow];
            NSArray *testArray = [self getMonthForYear:selectYear];
            return [testArray count];
        }
    }
    else
    {
        return [SAT_TEST_ADDRESS count];
    }
    return 0;
}

#pragma mark - UIPickerViewDelegate

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (_dataPickerType == DataPickerTypeTime)
    {
        NSArray *yearsArray = TEST_YEAR_ARRAY;
        if (component == 0)
        {
            if (row >= [yearsArray count])
            {
                return nil;
            }
            return [NSString stringWithFormat:@"%@年",[yearsArray objectAtIndex:row]];
        }
        else
        {
            NSUInteger selectedRow = [pickerView selectedRowInComponent:0];
            NSString *selectYear = [yearsArray objectAtIndex:selectedRow];
            NSArray *testArray = [self getMonthForYear:selectYear];
            
            if (row >= [testArray count])
            {
                return nil;
            }
            return [NSString stringWithFormat:@"%@月",[testArray objectAtIndex:row]];
        }

    }
    else
    {
        if (row >= [SAT_TEST_ADDRESS count])
        {
            return nil;
        }
        return [SAT_TEST_ADDRESS objectAtIndex:row];
    }
    return nil;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
    if (component == 0 && _dataPickerType == DataPickerTypeTime)
    {
        [pickerView reloadComponent:1];
    }
}


- (NSArray *)getMonthForYear:(NSString *)year
{
    NSArray *satArray = SAT_TEST_MONTH;
    NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init]autorelease];
    [dateFormatter setDateFormat:@"yyyy"];
    NSString *currentYearStr = [dateFormatter stringFromDate:[NSDate date]];
    
    if ([year isEqualToString:currentYearStr])
    {
        [dateFormatter setDateFormat:@"M"];
        NSString *currentMonthStr = [dateFormatter stringFromDate:[NSDate date]];

        NSMutableArray *months = [NSMutableArray arrayWithArray:satArray];
        for (NSString *month in satArray)
        {
            if ([month intValue] < [currentMonthStr intValue])
            {
                [months removeObjectAtIndex:[satArray indexOfObject:month]];
            }
        }
        return months;
    }
    else
    {
        return satArray;
    }

    return nil;
}

#pragma mark - SchoolRankingViewControllerDelegate

- (void)schoolRankingViewController:(SchoolRankingViewController *)viewController didSelectSchool:(NSString *)school
{
    if (IS_STRING_NOT_EMPTY(school))
    {
        _dreamSchoolLabel.text = school;
        _selectedMath.dreamschool = school;
    }
    else
    {
        if (IS_STRING_EMPTY(_selectedMath.dreamschool))
        {
            _dreamSchoolBtn.selected = NO;
        }
    }
}

@end
